<template>
  <!--  -->
  <div class="blog-mobile">
    <div class="head">
      <div class="g-con-m">
        <div class="page-title">
          {{ t('blog.pt1') }}
        </div>
        <Banner bannerModel="6" />
        <div class="tab-box">
          <ul
            class="tab-list noscrollbar"
            ref="tabList"
          >
            <li
              v-for="(item, index) in zoningList"
              :key="item"
              class="tab-item"
              @click="changeList(item)"
            >
              <div :class="['text', { active: queryForm.queryType == item.id }]">{{ item.zoningName }}</div>
            </li>
            <li
              class="tab-item"
              @click="changeList({ id: -1 })"
            >
              <div :class="['text', { active: queryForm.queryType == -1 }]">{{ t('blog.txt2') }}</div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="main">
      <div class="g-con-m">
        <div class="user">
          <div class="left">
            <div class="head-sculpture">
              <img
                :src="creatorInfo.avatar || creatorInfo.publishUserAvatar || defaultAvatar"
                alt=""
              />
            </div>
            <div class="name">
              <h2>{{ creatorInfo.customerName }}</h2>
              <p>{{ creatorInfo.label }}</p>
            </div>
          </div>
          <div class="right">
            <!-- <router-link v-if="memberGradeCode !== 'mfhy'" :to="'/mPublishArticle'"> -->
            <el-button type="primary" @click="handlePublish">{{ t('blog.actbtn') }}</el-button>
          </div>
        </div>
        <div class="list-box">
          <el-row
            class="item"
            v-for="(item, index) in listData"
            :key="index"
          >
            <el-col
              :span="24"
              class="user-info"
            >
              <div class="head-sculpture">
                <img
                  :src="item.avatar || item.publishUserAvatar"
                  alt=""
                />
              </div>
              <div class="name">
                <h2>{{ item.customerName || item.publishUserName }}</h2>
                <p>{{ item.label }}</p>
              </div>
            </el-col>
            <el-col
              :span="24"
              class="title mt-1"
            >
              <h1 @click.stop="routerPush(item)">{{ item.articleTitle }}</h1>
            </el-col>
            <el-col
              :span="24"
              class="content"
            >
              <!-- <div>
                {{ dateFormat(item.createTime, 2) + '--' + (item.articleText || item.content) }}
              </div> -->

              <div v-if="queryForm.queryType === -1">
                {{ toText(item.content, 140) }}
              </div>

              <div
                v-else
                class=""
              >
                <div style="font-size: 12px;">{{ dateFormat(item.createTime) }}</div>
                <div class="text noscrollbar" @click.stop="routerPush(item)">
                  {{ item.isShowMore ? item.articleText : toText(item.articleText, 150) }}
                  <span
                    v-if="item.articleText?.length > 150"
                    class="show-more"
                    @click="item.isShowMore = !item.isShowMore"
                  >
                    {{ item.isShowMore ? t('blog.b2') : `...${t('blog.b1')}` }}
                  </span>
                </div>


                <el-col
                  :span="24"
                  class="content"
                >
                  <ActicleComment
                    v-if="queryForm.zoningId !== -1"
                    :item="item"
                    @getList="getList"
                  />
                </el-col>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <!-- 发布文章 -->
    <el-dialog
      v-model="diaologVis"
      :title="'publish an article'"
      width="1000px"
    >
      <div class="divider"></div>
      <el-row>
        <el-col
          :span="10"
          class="user-info"
        >
          <div class="head-sculpture">
            <img
              :src="creatorInfo.avatar"
              alt=""
            />
          </div>
          <div class="name">
            <h2>{{ creatorInfo.customerName }}</h2>
            <p>{{ creatorInfo.label }}</p>
          </div>
        </el-col>
        <el-col :span="14">
          <el-input
            style="height: 40px"
            v-model="txtForm.articleTitle"
          ></el-input>
        </el-col>
        <el-col
          :span="24"
          class="mt-3 partition"
        >
          <span>*</span>
          Publish to partition：
        </el-col>
      </el-row>
      <div class="btn-list">
        <el-button
          :class="{ active: txtForm.zoningId == item.id }"
          v-for="(item, index) in zoningList"
          :key="index"
          @click="txtForm.zoningId = item.id"
          >{{ item.zoningNameCn }}</el-button
        >
      </div>
      <el-input
        type="textarea"
        resize="none"
        :autosize="{ minRows: 6, maxRows: 6 }"
        v-model="txtForm.articleText"
      ></el-input>
      <div class="mt-2">
        <Uploads
          ref="upload1"
          @change="setFileList"
        ></Uploads>
      </div>
      <el-button
        class="sub-btn mt-2 ml-c"
        @click="addArticle"
      >
        Publish an article
      </el-button>
    </el-dialog>
    <!-- 举报 -->
    <el-dialog
      v-model="reportDialog"
      :title="'举报这篇文章'"
      width="1000px"
    >
      <div class="divider"></div>
      <div class="mt-3 partition">
        <span>*</span>
        请选择举报类型：
      </div>
      <div class="btn-list mt-2">
        <el-button
          v-for="item in dictData.report_type"
          :class="{ active: reportForm.reportType == item.dictValue }"
          :key="item"
          @click="reportForm.reportType = item.dictValue"
        >
          {{ item.dictLabel }}</el-button
        >
      </div>
      <div class="mt-3 partition mb-2">
        <span>*</span>
        请输入举报详情
      </div>
      <el-input
        type="textarea"
        resize="none"
        :autosize="{ minRows: 6, maxRows: 6 }"
        v-model="reportForm.reportInfo"
      ></el-input>
      <div class="mt-3 partition mb-2">请上传举报截图</div>
      <div class="mt-2">
        <Uploads
          ref="upload2"
          @change="setReportFilelist"
        ></Uploads>
      </div>
      <div class="mt-2 mb-2">请提供详细的举报说明，便于我们更快处理。了解更多社区规则，请点击：<a href="#;"> 《船队经理网社区规范》</a></div>
      <el-button
        class="sub-btn mt-2 ml-c"
        @click="reportSub"
      >
        Publish an article
      </el-button>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Uploads from '@/components/Uploads.vue'
import { useI18n } from 'vue-i18n'
import { listPage, popularList, articleLike, articleCancelLike, getCustomerInfo, cancelFavorite, articleCollect, getZoningList, articleAdd, articleReport, getCommentList, getNoticesList } from '@/service/blog.js'
import { uploads } from '@/service/common.js'
import { dateFormat, toText, openUrl } from '@/utils/index'
import useDict from '@/hooks/useDict'
import useLogin from '@/stores/login'

import useClipboard from 'vue-clipboard3'
import ActicleComment from '@/components/ActicleComment.vue'
// 默认头像
const defaultAvatar = new URL('@/assets/img/icon_touxiang_01.png', import.meta.url)

const { toClipboard } = useClipboard()
const copy = async (text) => {
  try {
    await toClipboard(text)
    ElMessage.success(t('news.copy'))
  } catch (e) {}
}

const storeLogin = useLogin()

// 会员等级
const memberGradeCode = storeLogin.userInfo?.memberGradeCode

const { dictData, getDictData } = useDict()

const tabList = ref(null)
const router = useRouter()
const route = useRoute()
const { t, locale } = useI18n()
const reportDialog = ref(false)
const diaologVis = ref(false)
const zoningList = ref([])
const listData = ref([])
const hotListData = ref([])
const creatorInfo = ref({})
const platAnnouncement = ref('')
const txtForm = ref({
  zoningId: undefined,
  articleText: undefined,
  customerId: undefined,
  articleTitle: undefined,
  articlePicture: undefined
})
const reportForm = ref({
  articleId: undefined,
  customerId: undefined,
  reportInfo: undefined,
  reportType: undefined,
  reportScreenshot: undefined
})
const queryForm = ref({
  queryType: 0
  // queryType: -1
})
const currentPageIndex = ref(0)
const fileList = ref([])
const upload1 = ref(null)
const upload2 = ref(null)
const setFileList = (val) => {
  fileList.value = val
}
const page = ref({
  pageNum: 1, // 当前页码
  pageSize: 6 // 每页条数
})

// 上传
const handleUpload = (ref, list) => {
  return new Promise((resolve, reject) => {
    const newList = list.value.filter((item) => item.raw)
    const oldList = list.value.filter((item) => !item.raw).map((item) => item.url)

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls }) => {
        const resultFile = urls.split(',')
        list.value = resultFile.map((item) => {
          return {
            name: item.slice(item.lastIndexOf('/') + 1),
            url: item
          }
        })
        ref.value.setFileList(fileList.value)
        resolve([...oldList, ...resultFile])
      })
    } else {
      resolve(oldList)
    }
  })
}
const changeList = (item) => {
  page.value.pageNum = 1
  if (item.id != -1) {
    queryForm.value.queryType = item.id
    getList()
  } else {
    queryForm.value.queryType = -1
    getNoticesListFn()
  }
}
const getNoticesListFn = () => {
  getNoticesList(page.value).then((res) => {
    listData.value = res.rows
    platAnnouncement.value = res.total
  })
}
const getList = () => {
  listPage(page.value, queryForm.value).then((res) => {
    listData.value = res.rows.map((item) => {
      item.isShowMore = false
      item.imgList = item.articlePicture?.split(',')?.slice(0, 6)
      item.imgListAll = item.articlePicture?.split(',') || []

      item.commentFlag = false
      item.shareFLag = false
      item.likeFlag = item.isLike > 0 ? true : false
      item.collectFlag = item.isCollect > 0 ? true : false
      return item
    })
  })
}

// 
const handlePublish = ()=>{
  if(!storeLogin.userInfo) {
    ElMessage.warning(t('notLoginMsg'))
    openUrl('/login')
    return
  }

  openUrl('/mPublishArticle')
}

const hotList = () => {
  popularList().then((res) => {
    hotListData.value = res.data
  })
}
const nextFn = () => {
  if (currentPageIndex.value == Math.ceil(zoningList.value.length / 6) - 1) {
    return false
  } else {
    currentPageIndex.value = currentPageIndex.value + 1
    tabList.value.style.marginLeft = -(1260 * currentPageIndex.value) + 'px'
  }
}
const preFn = () => {
  if (currentPageIndex.value == 0) {
    return false
  } else {
    currentPageIndex.value = currentPageIndex.value - 1
    tabList.value.style.marginLeft = 1260 * currentPageIndex.value + 'px'
  }
}
const routerPush = (row) => {
  openUrl('/blogDetail', { id: row.id } )
}
//点赞||取消点赞
const changeLike = async (value, item) => {
  let data = {
    customerId: JSON.parse(localStorage.getItem('login')).userInfo.id,
    objType: 0,
    objId: item.id
  }
  if (value == 0) {
    item.likeFlag = true
    await articleLike(data).then((res) => {
      // ElMessage({
      //   message: '点赞成功',
      //   type: 'success'
      // })
    })
  } else {
    item.likeFlag = false
    await articleCancelLike(data).then((res) => {
      // ElMessage({
      //   message: '取消成功',
      //   type: 'success'
      // })
    })
  }
  // getList()
}
// 收藏|取消收藏
const changeCollect = async (value, item) => {
  let data = {
    customerId: JSON.parse(localStorage.getItem('login')).userInfo.id,
    // objType:0,
    articleId: item.id
  }
  if (value == 0) {
    item.collectFlag = true
    await articleCollect(data).then((res) => {
      // ElMessage({
      //   message: '收藏成功',
      //   type: 'success'
      // })
    })
  } else {
    item.collectFlag = false
    await cancelFavorite(data).then((res) => {
      // ElMessage({
      //   message: '取消成功',
      //   type: 'success'
      // })
    })
  }
  // getList()
}
const shareFlagChange = (item, value) => {
  item.shareFLag = value
}
//分享
const shareFn = (type) => {
  const { origin, pathname } = window.location
  const url = `${origin}${pathname}#/blogDetail?id=${id}`

  if (type == 'link') {
    copy(url)
  } else {
    generateQrCode({ link: window.location.href }).then((res) => {
      currentLinkImg.value = window.URL.createObjectURL(res)
      QrCodeVis.value = true
    })
  }
}
//新增文章
const addArticle = async () => {
  let res = await handleUpload(upload1, fileList)
  if (res.length) {
    txtForm.value.articlePicture = res.join()
  }
  let data = {
    ...txtForm.value,
    customerId: JSON.parse(localStorage.getItem('login')).userInfo.id
  }
  articleAdd(data).then((res) => {
    ElMessage({
      type: 'success',
      message: '发布成功'
    })
    txtForm.value = {
      zoningId: undefined,
      articleText: undefined,
      customerId: undefined,
      articleTitle: undefined,
      articlePicture: undefined
    }
    diaologVis.value = false
    getList()
  })
}
const reportFilelist = ref([])
const setReportFilelist = (val) => {
  reportFilelist.value = val
}
// 举报文章
const openReport = (row) => {
  reportForm.value.articleId = row.zoningId
  // reportDialog.value = true
}
const reportSub = async () => {
  let res = await handleUpload(upload2, reportFilelist)
  if (res.length) {
    reportForm.value.reportScreenshot = res.join()
  }
  let data = {
    ...reportForm.value,
    customerId: JSON.parse(localStorage.getItem('login')).userInfo.id
  }
  articleReport(data).then((res) => {
    ElMessage({
      type: 'success',
      message: '举报成功'
    })
    reportForm.value = {
      articleId: undefined,
      customerId: undefined,
      reportInfo: undefined,
      reportType: undefined,
      reportScreenshot: undefined
    }
    reportDialog.value = false
    getList()
  })
}
// 评论列表
const getCurComment = (row) => {
  getCommentList({ articleId: row.id, pageNum: 1, pageSize: 10 }).then((res) => {
    row.commentList = res.rows
    row.commentFlag = true
  })
}

const getCustomerInfoFn = () => {
  const customerId = storeLogin?.userInfo?.id
  if (!customerId) return
  getCustomerInfo({ customerId }).then((res) => {
    creatorInfo.value = res.data
  })
}

const init = async () => {
  await getDictData('report_type')
  // getList()
  // hotList()
  getCustomerInfoFn()
  getZoningList().then((res) => {
    zoningList.value = res.data
  })
  getList()
}

onMounted(() => {
  init()
})
</script>

<style scoped lang="scss">
.blog-mobile {
  .head {
    padding-bottom: 15px;
    position: relative;

    .page-title {
      background: #252628;
      color: #fff;
      padding: 12px 20px;
      font-weight: bold;
    }

    .head-portrait {
      margin-top: -80px;
      margin-left: 25px;

      img {
        width: 160px;
        height: 160px;
        border: 2px solid #fff;
        border-radius: 50%;
        display: block;
        background: #fff;
      }
    }

    .name {
      font-weight: bold;
      font-size: 14px;
    }

    .btn {
      .el-button {
        height: 44px;
        text-transform: uppercase;
        font-weight: bold;
      }
    }

    .tab-box {
      width: 100%;
      // height: 72px;

      .tab-list {
        white-space: nowrap;
        overflow-x: scroll;

        .tab-item {
          display: inline-block;
          cursor: pointer;

          .text {
            font-size: 14px;
            color: #252628;
            border-bottom: 2px solid black;
            // text-indent: 24px;
            padding: 0 20px;
            height: 50px;
            line-height: 50px;
          }

          .active {
            border-bottom: 4px solid rgba(202, 42, 2, 1);
          }
        }
      }
    }
  }

  .main {
    background: white;
    .user {
      width: 100%;
      padding: 10px;
      background: white;
      display: flex;
      justify-content: space-between;
      .left {
        display: flex;
        .head-sculpture {
          img {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-right: 12px;
          }
        }
        .name {
          h2 {
            font-size: 14px;
            font-weight: bold;
            color: #252628;
          }

          p {
            font-size: 14px;
            font-weight: 400;
            color: #9d9fa5;
          }
        }
      }
      .right {
        button {
          // width: 200px;
          // height: 80px;

          font-weight: 400;
          color: #ffffff;
        }
        :deep(.el-button--primary) {
          span {
            font-size: 14px;
          }
        }
      }
    }
    .list-box {
      width: 100%;
      overflow-y: auto;
      padding: 10px;
      background: white;

      .item {
        background: rgba(245, 245, 245, 1);
        margin-bottom: 25px;
        padding: 10px;
        cursor: pointer;

        &:last-child {
          margin-bottom: 0;
        }

        .user-info {
          display: flex;

          .head-sculpture {
            img {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              margin-right: 12px;
            }
          }

          .name {
            h2 {
              font-size: 12px;
              font-weight: bold;
              color: #252628;
              .date {
                font-weight: 400;
                color: #9d9fa5;
              }
            }

            p {
              font-size: 14px;
              font-weight: 400;
              color: #9d9fa5;
            }
          }
        }

        .title {
          font-size: 16px;

          font-weight: bold;
          color: #252628;
        }

        .content {
          font-weight: 400;
          color: #6a6973;
          line-height: 24px;
          max-width: 100%;
          white-space: pre-line;
          overflow-wrap: break-word;
          div {
            font-size: 14px;
          }

        }

      }
    }
  }
}

.partition {
  font-size: 16px;

  font-weight: bold;
  color: #252628;

  span {
    color: rgba(202, 42, 2, 1);
  }
}

.btn-list {
  width: 100%;
  display: flex;
  margin-top: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  justify-content: space-between;

  button {
    border-radius: 0px;
    background: rgb(250, 198, 185);
    font-size: 12px;

    font-weight: 400;
    color: #1c1e22;
    border: 1px solid rgb(250, 198, 185);
    margin-top: 20px;
  }

  .active {
    border: 1px solid rgba(202, 42, 2, 1);
    background: rgba(202, 42, 2, 1);
    color: white;
  }
}

.sub-btn {
  min-width: 100px;
  max-width: 340px;
  height: 40px;
  background: #252628;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 400;
  color: #ffffff;
}

.g-con-m {
  padding: 0px;
}
</style>
